package com.dhnsoft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dhnsoft.po.Commodity;
import com.dhnsoft.po.Order;
import com.dhnsoft.po.Shopping;
import com.dhnsoft.service.admin.AdminService;
import com.dhnsoft.service.commodity.CommodityService;
import com.dhnsoft.service.order.OrderService;
import com.dhnsoft.service.order.PayLogService;
import com.dhnsoft.service.shopping.ShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ShoppingService shoppingService;

    @Autowired
    private PayLogService payLogService;

    @GetMapping("createOrder")
    public String createOrder( Model model){
        QueryWrapper<Shopping> wrapper = new QueryWrapper<>();
        Shopping commodity = shoppingService.getOne(wrapper);
        //创建订单，返回订单号
        Order order = orderService.createOrders(commodity);
        model.addAttribute("order",order);
        return "order";
    }



    //生成微信支付二维码
    @RequestMapping("createNative")
    public String createNative(String orderNo,Model model){
        //返回信息，包含二维码地址和其他信息
        Map map = payLogService.createNative(orderNo);
        System.out.println("返回二维码map集合:"+map);
        model.addAttribute("map",map);
        return "payLog";
    }

    //查询订单支付状态
    //参数：订单号，根据订单号查询 支付状态
    @GetMapping("queryPayStatus")
    @ResponseBody
    public Integer queryPayStatus( String orderNo,Model model){
        System.out.println("11211"+orderNo);
        Map<String,String> map = payLogService.queryPayStatus(orderNo);
        System.out.println("***查询订单状态map集合:"+map);
        if(map==null){
            model.addAttribute("msg","支付出错了");
            return 1;
        }
        //如果返回map里面不为空,通过map获取订单状态
        if(map.get("trade_state").equals("SUCCESS")){
            //添加记录到支付表，更新订单表订单状态
            payLogService.updateOrderStatus(map);
            model.addAttribute("msg","支付成功");
            QueryWrapper<Shopping> wrapper = new QueryWrapper<>();
            shoppingService.remove(wrapper);
            System.out.println("支付成功");
            return 2;
        }
        model.addAttribute("msg","支付中");
        return 3;
    }


}
